/**
 * Loads data into the global data variable for use in the bar
 * and scatterplot visualizations.
 * 
 * dept - string representing department (Ex, CS)
 * num - string representing the course num (Ex, 1301)
 * opts-
 *      .start- integer representing start semester (1-19)
 *      .end- integer representing the stop semester (1-19)
 * returns - the appropriate data
 */
var get_data = function(dept, num, opts) {
	// Filtering function options
	if (!opts.start) {
			opts.start = semester_start;
	}               
	if (!opts.end) {
			opts.end = semester_end;
	}
	if (!opts.gpa_start) {
			opts.gpa_start = start_gpa;
	}
	if (!opts.gpa_end) {
			opts.gpa_end = end_gpa;
	}
	// Finds which classes are checked
	var checked_professors = [];
	if (!opts.new_class) {  // Only do this if the function call did not ask for a new class
			$(":checkbox:checked").each( 
			function() { 
					if (this.checked) {      
						checked_professors.push('prof[]=' + this.value.split(',')[0]);
					}
			});
	}
	
	// Construct query by adding professors to query
	var pconcat = checked_professors.length ? "&" + checked_professors.join('&') : "";
	// Make AJAX call to get department data based on department, course number
	//  start and end semesters, gpa start and end, and professors
	$.ajax({
	  url: 'http/ccHTTP.php?action=get_rows_w_date&dept_code='+dept+'&course_num='+num+'&start='+opts.start+'&end='+opts.end + '&start_gpa=' +opts.gpa_start + '&end_gpa='+opts.gpa_end + pconcat,
	  async: false,
	  dataType: 'json',
	  success: function (response) {
		data = response; // Set data to the json based response from ccHTTP.php
		
		// Sort data based on the id attribute of radio buttons
		sort_type = $("input[@name=radio]:checked").attr("id");
		// Sort based on GPA
		if (sort_type == "gpa") {

			data = response.sort(function(a,b) {
				return a.GPA - b.GPA;
			});
		}
		// Sort based on professor (though we did not fully implement this function)
		else if (sort_type == "professor") {
			data = response.sort(function(a,b) {
				return a.LastName - b.LastName;
			});
		}
		// Otherwise sort based on date
		else {
			data = response.sort(function(a,b) {
				if(a.Year != b.Year){
					return a.Year - b.Year;
				}
				var aVal, bVal;
				// Figure out order based on Fall,Summer since they do not give numbers for term
				if(a.Semester == "Fall")
					aValue = 2;
				else if(a.Semester == "Summer")
					aValue = 1;
				else
					aValue = 0;
				if(b.Semester == "Fall")
					bValue = 2;
				else if(b.Semester == "Summer")
					bValue = 1;
				else
					bValue = 0;
				return aValue - bValue;
			});
		}
	  }
	});     
    
	//Update info tag to have course department and number
    $("#info").html("<h3>"+department+ course_number+"</h3>");

}

// Get average CIOS data and load into the global cios_data variable
var get_cios_data = function() {

	$.ajax({
	  url: 'http/ccHTTP.php?action=get_cios_avgs',
	  async: false,
	  dataType: 'json',
	  success: function (response) {
		cios_data = response; 
	  }
	});     

}

/**
 * Populate the autocomplete section with the proper data.
 * Re-Render visualization when user selects new class.
 */
$(function() {
	$.ajax({
	  url: 'http/courseNames.php',
	  async: false,
	  dataType: 'json',
	  success: function (response) {
	  	// Use the jQuery auotcomplete function
		$( "#autocomplete" ).autocomplete({
			source: response,
			minLength: 3, // Set min length of search to 3 so that 1 letter such as C does not match many things
			select: function( event, ui ) {
				// When an item was selected
				if (ui.item) {
					// get_data based on entered value
					var toParse = ui.item.value;
					// Find place that separates the digits from the rest
					var delim = toParse.search(/\d/);
					// Extract department
					department = toParse.substr(0,delim);
					// Extract course number
					course_number = toParse.substr(delim);
					// Refresh the data
					get_data(department, course_number, {new_class : true});
					// Render professor checkboxes
					pp();
					// Render the visualizations based on the new data
					vis_bar.render();
					vis_scat.render();
				}	
			}
		});
	  }
	});	
});

var threshold = 50; // if num cases less than threshold
					 // then slider will update as the user drags
					 
/**
 * Controlling the semester slider, called when the page loads
 */
$(function() {
	// Load term information based on logical id
	var term = [];
	$.ajax({
	  url: 'http/ccHTTP.php?action=get_terms',
	  async: false,
	  dataType: 'json',
	  success: function (terms_response) {
		$.each(terms_response, function(index, value) {
			// Set the text of the term to be the first 3 characters of the semester and the year
			term[value.o_id] = value.semester[0]+value.semester[1]+value.semester[2] + " " + value.year;
		});
	  }
	});	
	// Use jQuery's slider method
	$( "#slider-range-semester" ).slider({
		range: true,
		min: 1,
		max: term.length-1,
		values: [1, term.length-1],
		slide: function( event, ui ) {
			// Set the label of the slider
			$( "#amount" ).val(term[ ui.values[ 0 ] ]+ " - " + term[ ui.values[ 1 ] ] );
			// Set the global variables semester_start and semester_end based on slider values
			semester_start = ui.values[ 0 ];
			semester_end = ui.values[ 1 ]; 
			// Only render the immediately if the data is small, otherwise wait until the user stops
			if (data.length < threshold) { 
				get_data(department, course_number, {start:ui.values[ 0 ], end:ui.values[ 1 ], new_class:true});
				pp(); // Render professor checkboxes
				vis_bar.render();
				vis_scat.render();
			}
			
			
		},
		// Refresh data when user stops
		stop: function ( event, ui ){
			get_data(department, course_number, {start:ui.values[ 0 ], end:ui.values[ 1 ], new_class:true});
			pp();
			vis_bar.render();
			vis_scat.render();
		}
	});
	// Set the semester label
	$( "#amount" ).val(term[$("#slider-range-semester").slider("values",0)]+
		" - " + term[$( "#slider-range-semester" ).slider( "values", 1 )] );
	});
	
/** 
 * controlling the GPA slider, See comments above for slider interactions
 */
$(function() {
	$( "#slider-range-gpa" ).slider({
		range: true,
		min: 0.0,
		max: 4.0,
		values: [0.0, 4.0],
		step: 0.1,
		slide: function( event, ui ) {
			$( "#amount-gpa" ).val( ui.values[ 0 ] + " - " + ui.values[ 1 ] );
			start_gpa = ui.values[ 0 ];
			end_gpa = ui.values[ 1 ]; 
			
			
			if (data.length < threshold) { 
				get_data(department, course_number, {gpa_start:start_gpa, gpa_end:end_gpa, new_class:true});
				pp();
				vis_bar.render();
				vis_scat.render();
			}
			
		},
		stop: function ( event, ui ){
			get_data(department, course_number, {gpa_start:start_gpa, gpa_end:end_gpa, new_class:true});
			pp();
			vis_bar.render();
			vis_scat.render();
			
			
		}
	});
	$( "#amount-gpa" ).val( $( "#slider-range-gpa" ).slider( "values", 0 ) +
		" - " + $( "#slider-range-gpa" ).slider( "values", 1 ) );
});

/**
 * function to handle creation of professor menu
 */
function pp() {
	// Uncheck all checkboxes
	$(":checkbox:checked").each( 
	function() { 
		this.checked = false;
	});	
	// Empty the profs HTML element
	$("#profs").html("");
	// Clear professors variable
	professors = [];
	// Find unique professors
	var prof;
	var c = 0;
	for (var i = 0; i < data.length; i++) { 
		prof = data[i].LastName + ", " + data[i].FirstName;
		if (professors.indexOf(prof) == -1) {
			professors[c] = prof; c++;
		}
	}
	
	// With each of the professors append a checkbox to the profs HTML element
	var topicContainer = $('#profs');
	$.each( professors, function( iteration, item )
	{
		$('#profs').append(
				// Append checkbox for professor
				$(document.createElement("input")).attr({
						 id:    'topicFilter-' + item
						,name:  item
						,value: item
						,type:  'checkbox'
						,class: 'prof-box'
						,checked:true
				})
				// Set click event to rerender the visualization with the new professor information
				.click( function( event )
				{
					get_data(department,course_number,{});
					vis_scat.render();
					vis_bar.render();
				} )
				
		)
		// Add label to checkboxes
		.append(
				$(document.createElement('label')).attr({
						'for':  'topicFilter' + '-' + item
				})
				.text( item )
		).append("<br/>")
		
	} );
}

$(function()
{
	// When the sorting buttons are clicked, refresh the data and rerender the visualizations 
	$('input.sort').click( function( event )
	{
		get_data(department, course_number, {});
		pp();
		vis_bar.render();
		vis_scat.render();
	})
});
